﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using LeoShi.Soft.OpenSinaAPI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using TCS.DBUtility;
using TCS.Model.Weibo;
using System.Xml;
using LTP.Common;
using WeiBo.SinaAPI;
using System.Web.UI.HtmlControls;

namespace TCS.Web.MembersHome
{
    public partial class WeiboCommenet : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                if ((Session["BangShangMember"] != null) || (Session["BangShangMember"].ToString() != ""))
                {
                    BindRdoBtn();//绑定按钮
                    BindComment();

                }
                else
                {
                    Response.Redirect("~/membersHome/login.aspx");
                }
            } 

           
        }
        //public void BindComment() 
        //{
        //    int memberId = Convert.ToInt32(Session["memberid"].ToString());
        //    string commentSql = " Member_id="+memberId;
        //    DataSet commds = new TCS.BLL.Weibo.WeiBo_Comment().GetList(commentSql);
        //    if (commds.Tables[0].Rows.Count > 0)
        //    {
        //        rptComments.DataSource = commds;
        //        rptComments.DataBind();
        //    }
        //    else
        //    {
        //        InsertCommentsOfMember();
        //    }
        
        //}
        /// <summary>
        /// 按条件绑定评论数据
        /// </summary>
        public void BindComment()
        {
            DataSet fans = null;
            DataSet followers = null;
            if(!rdoAllPerson.Checked)  //如果不是按人数显示全部
            {
            long userId = long.Parse(Session["memberid"].ToString());//帮商会员id
            string fanSql = " UserID=" + userId;   //粉丝
            string follSql = " UserID=" + userId; //关注
             fans = new TCS.BLL.Weibo.WeiBo_FansInfo().GetList(fanSql);
             followers = new TCS.BLL.Weibo.WeiBo_followersInfo().GetList(follSql);

            }
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.GET);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            if(rdoSendAndReceiveComm.Checked)
                  Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_timeline.json";//我的所有的评论
            if(rdoSendComm.Checked)
                Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_by_me.json"; //我发出评论
            if(rdoReceivedComm.Checked)
                Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_to_me.json";//我收到评论
            if (!rdoSendComm.Checked)  //如果评论不是我发出的就不能删除评论
                this.btnDeletComment.Enabled = false;
            else
                this.btnDeletComment.Enabled = true;
            string url = Session["CommentsAPI"].ToString();
            string result = httpRequest.Request(url,String.Empty);
            List<Comment> listComment = JSONConvert.DeserializeJsonToListObjectComment(result);
            List<Comment> listComment2 = new List<Comment>();
            List<Comment> listComment3 = new List<Comment>();
            List<Comment> listComment4 = new List<Comment>();
            //按状态
            foreach (Comment comment in listComment)
            {

                if (rdoAllCommend.Checked)  //全部
                {
                    listComment2 = listComment;
                }
                if (rdoIsCommend.Checked)   // 回复
                {
                    if (comment.reply_comment!=null)
                    {
                        listComment2.Add(comment);
                    }
                }
                if (rdoNotCommend.Checked)    //未回复
                {
                    if (comment.reply_comment== null)
                    {
                        listComment2.Add(comment);
                    }
                }
            }
            //安人筛选
            foreach (Comment comment2 in listComment2)
            {

                if (rdoAllPerson.Checked)
                {
                    listComment3 = listComment2;
                }
                if (rdoFollower.Checked)  //我的粉丝
                {
                    for (int i = 0; i < fans.Tables[0].Rows.Count; i++)
                    {
                        if (comment2.user.id == fans.Tables[0].Rows[i]["FansWBId"].ToString())  //如果我的粉丝表中有
                        {
                            listComment3.Add(comment2);
                        }
                    }
                }
                if (rdoFriend.Checked)   // 我关注的
                {
                    for (int i = 0; i < followers.Tables[0].Rows.Count; i++)
                    {
                        if (comment2.user.id== followers.Tables[0].Rows[i]["FansId"].ToString())  //如果我的粉丝表中有
                        {
                            listComment3.Add(comment2);
                        }
                    }
                }
                if (rdoVUser.Checked)    //认证用户
                {
                    if (comment2.user.verified!= "false")
                    {
                        listComment3.Add(comment2);
                    }
                }
                if (rdoStranger.Checked)  //陌生人
                {
                    //if (comment2.user.id != fans.Tables[0].Rows[i]["FansWBId"].ToString())  //如果我的粉丝表
                    //{
                    //    listComment3.Add(comment2);
                    //}
                }
            }
            foreach(Comment comment3 in listComment3)
            {
                int count=0;
                if(txtCout.Text!="")
                {
                    count = int.Parse(txtCout.Text.ToString());
                }
                if (txtCout.Text.ToString() == "")
                {
                    listComment4 = listComment3;
                } 
                else
                {
                    if(comment3.text.ToString().Length>count)
                    {
                        listComment4.Add(comment3);
                    }
                    
                }
             
            }
            //按时间筛选
            lblCount.Text = listComment4.Count.ToString();
            rptComments.DataSource = listComment4;
            rptComments.DataBind();

        }
        public static DataSet ConvertXMLToDataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                //从stream装载到XmlTextReader
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }

        protected void rdoSendAndReceiveComm_CheckedChanged(object sender, EventArgs e)
        {
            Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_timeline.json";
            rdoSendComm.Checked = false;
            rdoReceivedComm.Checked = false;
        }

        protected void rdoReceivedComm_CheckedChanged(object sender, EventArgs e)
        {
            Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_to_me.json";
            rdoSendAndReceiveComm.Checked = false;
            rdoSendComm.Checked = false;
        }

        protected void rdoSendComm_CheckedChanged(object sender, EventArgs e)
        {
            Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_by_me.json";
            rdoSendAndReceiveComm.Checked = false;
            rdoReceivedComm.Checked = false;
        }
        //绑定单选按钮默认值
        private void BindRdoBtn()
        { 
          if(rdoReceivedComm.Checked==true)
          {
              rdoSendAndReceiveComm.Checked = false;
              rdoSendComm.Checked = false;
              Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_to_me.json";
              //Session["IReceivedAndReplyComment"] =null;
              //Session["IReplyComment"] = null;
          }
          if (rdoSendAndReceiveComm.Checked == true)
          {
              Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_timeline.json";
              //Session["IReplyComment"] =null;
              //Session["IReceivedComment"] =null;
              rdoSendComm.Checked = false;
              rdoReceivedComm.Checked = false;
          }
          if (rdoSendComm.Checked == true)
          {
              Session["CommentsAPI"] = "http://api.t.sina.com.cn/statuses/comments_by_me.json";
              //Session["IReceivedAndReplyComment"] = null;
              //Session["IReceivedComment"] = null;
              rdoSendAndReceiveComm.Checked = false;
              rdoReceivedComm.Checked = false;
          }

           
           
        }

        /// <summary>
        /// 回复评论
        /// </summary>
        protected void rptComments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
            //var url = "http://api.t.sina.com.cn/statuses/comment.xml"; //对微博进行评论

            string url="http://api.t.sina.com.cn/statuses/reply.xml";

            string text=((TextBox)(e.Item.FindControl("txtComment"))).Text.ToString();
            long id = long.Parse(((HiddenField)e.Item.FindControl("HidCommentID")).Value);
            long cid = Convert.ToInt64(e.CommandArgument.ToString());
            string aa="cid="+cid+"  uid="+id+" 内容："+text;
            if (e.CommandName == "Comment")
            {

                lblCount.Text = aa;
                this.lblResult.Text = aa;
              
                httpRequest.Request(url, "comment=" + HttpUtility.UrlEncode(text) + "&id=" + id + "&cid=" + cid + "");
                this.lblResult.Text ="OK";
            }
        }
        /// <summary>
        /// 批量删除评论信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeletComment_Click(object sender, EventArgs e)
        {
            var httpRequest = HttpRequestFactory.CreateHttpRequest(Method.POST);
            httpRequest.Token = Session["oauth_token"].ToString();
            httpRequest.TokenSecret = Session["oauth_token_secret"].ToString();
            httpRequest.UserRemoteIP = Request.UserHostAddress;
           string url = "http://api.t.sina.com.cn/statuses/comment_destroy/:id.json";
                   // string url = "http://api.t.sina.com.cn/statuses/comment_destroy/:id.json";
                    //http://api.t.sina.com.cn/statuses/comment_destroy
          //  string url = "http://api.t.sina.com.cn/statuses/comment/destroy_batch.json";
             string  itemId = "";
            if (!rdoSendComm.Checked)  //如果评论不是我发出的就不能删除评论
            {
                this.btnDeletComment.Enabled=false;
                return;
            }
            foreach (RepeaterItem item in this.rptComments.Items)
            {
                CheckBox cb = (CheckBox)item.FindControl("chkItem");
                if (cb.Checked ==true)
                {
                   long  id = Convert.ToInt64(((HtmlInputHidden)item.FindControl("hfID")).Value);
                    // 删除评论
                  
                    try
                    {
                        itemId += id + ",";
                        string result = httpRequest.Request(url,"id="+id);
                    }
                    catch (System.Data.OleDb.OleDbException E)
                    {
                        throw new Exception(E.Message);
                    }
                    finally
                    {

                    }
                }
            }
            //itemId = itemId.Substring(0,itemId.Length-1);
            //string result = httpRequest.Request(url,"ids="+itemId);
            BindComment();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindComment();
        }
        //时间转换
        public string SinaDateConvert(object obj)
        {
            string result = DateTime.Now.ToString();
            result = StringHelper.SinaDataConvert(obj.ToString());
            return result;
        }
    }

}
